package vehicles;

import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

public class MonitorVehicleTracker {

	private final Map<String, Point> locations;

	
	public MonitorVehicleTracker(Map<String, Point> data) {
		locations = deepCopy(data);
	}

	private Point safeGet(String name) {
		Point loc = locations.get(name);
		if (loc == null) throw new IllegalArgumentException("Illegal name");
		return loc;
	}
	
	public synchronized Point getLocation(String name) {
		// copying for thread-safety
		return new MutablePoint(safeGet(name));
	}
	
	public synchronized void setLocation(String name, Point point) {	
		// bad job!!!
		MutablePoint loc = (MutablePoint)safeGet(name);

		loc.x = point.getX();
		loc.y = point.getY();
	}
	
	public synchronized Map<String, Point> getLocations() {
		// deep copying
		return Collections.unmodifiableMap(deepCopy(locations));
	}

	private Map<String, Point> deepCopy(Map<String, Point> data) {
		Map<String, Point> copy = new HashMap<>();
		for (String s : data.keySet()) {
			Point point = data.get(s);
			copy.put(s, new MutablePoint(point.getX(), point.getY()));
		}
		return copy;
	}
}
